<template>
  <div>
    <header class="page-header mb20">
      <el-row :gutter="24">
        <el-col :span="7">
          <el-input @keydown.native.13="getDataList" v-model.trim="searchKeyword"
                    placeholder="搜索筛选项" suffix-icon="el-icon-search"/>
        </el-col>
        <el-col :span="17" class="text-right">
          <el-button icon="el-icon-plus" @click="addFilter" type="primary">新增筛选项</el-button>
          <el-button icon="el-icon-minus" @click="rmFilters" type="danger">删除筛选项</el-button>
        </el-col>
      </el-row>
    </header>
    <div class="table-container">
      <el-table :data="dataList" @selection-change="onSelectFilters">
        <el-table-column type="selection" class-name="text-center" label-class-name="text-center"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="筛选项分类" prop="catalogItemName"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="筛选项参数" prop="parameterTerm"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="选项值" prop="valueItems"></el-table-column>
        <el-table-column label="模糊匹配" width="100px" prop="fuzzyMatching" class-name="text-center" label-class-name="text-center"></el-table-column>
        <el-table-column label="排序" prop="serialNumber" width="60px" class-name="text-center" label-class-name="text-center"></el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="创建时间" prop="createTime" class-name="text-center" label-class-name="text-center"></el-table-column>
        <el-table-column label="操作"  min-width="150px" class-name="text-center" label-class-name="text-center">
          <template slot-scope="scope">
            <a href="/" @click.prevent="editParam(scope.row)" class="text-warning">编辑</a>
            <a href="/" @click.prevent="edit(scope.row)" class="text-warning">编辑筛选项</a>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="onCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </div>

    <!--新增筛选项弹窗 title="新增筛选项"-->
    <el-dialog

      :visible.sync="addFilterDialog"
      width="70%">
      <!--新增筛选项表单-->
      <el-form :model="filter" ref="filterForm" label-width="100px">
        <el-form-item label="所属目录" v-if="!(filterDialogAction === 'updateParam')">
          <el-input v-model="filter.name" disabled style="width: 230px"></el-input>
        </el-form-item>

        <el-form-item
          v-if="!(filterDialogAction === 'updateParam')"
          label="分类名称"
          prop="productProgramItemName"
          :rules="[
            {required: true, message: '分类名称不能为空', trigger: 'blur'},
            {validator: validtateNameRepeat, trigger: 'blur'},
          ]">
          <el-input v-model="filter.productProgramItemName" placeholder="请输入筛选项名称" style="width: 230px"></el-input>
        </el-form-item>

        <el-form-item label="筛选项参数" >
          <div class="filter-params" v-for="(param, index) in filter.productProgramItemList" :key="index">
            <el-row :gutter="0">
              <el-col :span="6">
                <el-form-item
                  label="参数名称"
                  :prop="'productProgramItemList.' + index + '.parameterTerm'"
                  :rules="{
                      required: true, message: '参数不能为空', trigger: 'blur'
                   }">
                  <el-input placeholder="输入参数" v-model="param.parameterTerm"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item
                  label="排序"
                  :prop="'productProgramItemList.' + index + '.serialNumber'"
                  :rules="{
                      required: true, message: '排序不能为空', trigger: 'blur'
                   }">
                  <el-input placeholder="输入排序" v-model="param.serialNumber"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="模糊匹配">
                  <el-checkbox true-label="Y" false-label="N" v-model="param.fuzzyMatching"></el-checkbox>
                </el-form-item>
              </el-col>

              <el-col :span="3" class="text-right" v-if="!(filterDialogAction === 'updateParam')">
                <i class="el-icon-delete" @click="rmParam(filter, index)"></i>
              </el-col>
            </el-row>

            <el-row class="filter-values" >
              <el-col :span="24">
                <el-form-item label="参数值">
                  <el-form-item
                    v-for="(value, index2) in param.productProgramItemSonList"
                    :key="index2"
                    :prop="'productProgramItemList.' + index + '.productProgramItemSonList.' + index2 + '.parameterValues'"
                    :rules="{
                      required: true, message: '参数值不能为空', trigger: 'blur'
                   }"
                    class="value">
                    <el-input v-model="value.parameterValues" size="mini">
                      <el-button slot="append" @click="rmValue(param, index2)" icon="el-icon-minus"></el-button>
                    </el-input>
                  </el-form-item>
                  <el-button size="mini" icon="el-icon-plus" @click="addValue(param)" type="primary"></el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-button
            type="primary"
            v-if="!(filterDialogAction === 'updateParam')"
            icon="el-icon-plus" @click="addParam(filter)" style="width: 100%">
            添加筛选项参数
          </el-button>
        </el-form-item>

        <el-form-item class="text-center">
          <el-button type="primary" @click="submit('filterForm')">确定</el-button>
          <el-button type="danger" @click="addFilterDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    props: ['currentCatalog'],
    data () {
      return {
        // 筛选项查询状态
        status: 1,

        // 表格数据
        dataList: [],
        currentPage: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,

        searchKeyword: '',
        // 选中的solutions
        selectFilters: [],
        // add
        addDialog: false,
        solution: {},
        filterDialogAction: '',
        labelWidth: '100px',

        // 新增筛选项
        addFilterDialog: false,
        filter: {
          name: this.currentCatalog.name,   // 所属分类
          productProgramItemName: '',       // 名称
          productProgramItemList: [
            { parameterTerm: '', serialNumber: '', fuzzyMatching: 'Y', productProgramItemSonList: [{parameterValues: '1'}, {parameterValues: '2'}, {parameterValues: '3'}] },
          ]
        }
      }
    },
    created () {
      // this.getDataList()
    },
    watch: {
      'currentCatalog' () {
        if (this.currentCatalog.id) {
          this.filter.name = this.currentCatalog.name
          this.getDataList()
          this.filter.solution = this.currentCatalog.name
        }
      }
    },
    mounted () {
      // this.getFilters()
    },
    methods: {
      // 编辑筛选项
      edit (filter) {
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-prod/product/programDir/queryProductProgramC'),
          method: 'post',
          data: this.$http.adornData({id: filter.id})
        }).then(data => {
          if (data && data.code === 0) {
            this.filter = data.data || {}
            this.filterDialogAction = 'update'
            this.addFilterDialog = true
            this.tempClassifyName=data.data.productProgramItemName
          }
        })
      },

      // 筛选项分类名称重复校验
      validtateNameRepeat (rule, value, callback) {
        if(this.tempClassifyName==value){
            callback()
            return
        }
        const params = {
          programDirectoryId: this.currentCatalog.id,
          catalogItemName: value
        }
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-prod/product/programDir/isExistence'),
          method: 'post',
          data: this.$http.adornData(params)
        }).then(data => {
          if (data.data && data.data > 0) {
            callback(new Error('筛选项分类名称已存在'))
          } else {
            callback()
          }
        })
      },

      // 编辑/保存
      submit (formName) {
        let self=this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(this.filter)
            let params = {}
            let url = ''
            switch (this.filterDialogAction) {
              // 添加
              case 'add':
                params.id = this.currentCatalog.id
                url = '/prm-os-srv-prod/product/programDir/saveProductProgramC'
                break;

              // 更新
              case 'update':
                url = '/prm-os-srv-prod/product/programDir/updateProductProgramC'
                break;

              case 'updateParam':
                url = '/prm-os-srv-prod/product/programDir/updateProductProgramD'
                break;
            }


            this.$http({
              url: this.$http.adornUrl(url),
              method: 'post',
              data:this.$http.adornData(Object.assign({}, params, this.filter))
            }).then(data => {
              if (data && data.code === 0) {
                this.addFilterDialog = false
                // 重置条件
                this.currentPage = 1
                this.searchKeyword = ''
                this.$refs[formName].resetFields()
                this.getDataList()
              }
            })
          }
        })
      },
      // 新增筛选项
      addFilter () {
        this.filterDialogAction = 'add'
        this.addFilterDialog = true
        this.filter = {
          name: this.currentCatalog.name,   // 所属分类
          productProgramItemName: '',       // 名称
          productProgramItemList: [
            { parameterTerm: '', serialNumber: '', fuzzyMatching: 'Y', productProgramItemSonList: [{parameterValues: ''}] },
          ]
        }
      },

      // ============== 添加筛选项弹窗参数操作
      // 添加参数
      addParam (filter) {
        filter.productProgramItemList.push({
          parameterTerm: '',
          serialNumber: '',
          fuzzyMatching: 'Y',
          productProgramItemSonList: [{parameterValue: ''}]
        })
      },
      // 删除参数
      rmParam (filter, index) {
        filter.productProgramItemList.splice(index, 1)
      },
      // 修改单个参数
      editParam (param) {
        this.filterDialogAction = 'updateParam'
        this.addFilterDialog = true
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-prod/product/programDir/queryProductProgramD'),
          method: 'post',
          data: this.$http.adornData({id: param.id})
        }).then(data => {
          if (data && data.code === 0) {
            this.filter = data.data || {}
          }
        })
      },
      // ================================

      // ============== 添加筛选项弹窗值操作
      // 添加值
      addValue (param) {
        param.productProgramItemSonList.push({parameterValues: ''})
      },
      // 删除值
      rmValue (param, index) {
        param.productProgramItemSonList.splice(index, 1)
      },

      // ================================

      // 修改编辑筛选项
      editFilter (filter) {
        this.filterDialogAction = 'edit'
        this.filter = {
          params: [
            {name: filter.paramName, sort: filter.sort, isRequired: filter.isRequired, values: filter.values}
          ]
        }
        this.addFilterDialog = true
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true

        // 0020根据产品目录id和筛选项信息查询筛选项参数列表
        this.$http({
          url: this.$http.adornUrl('/prm-os-srv-prod/product/program/queryProductClassifyConditionList'),
          method: 'post',
          data: this.$http.adornParams({
            pageNo: this.currentPage - 1,
            pageSize: this.pageSize,
            programDirectoryId: this.currentCatalog.id,
            parameterTerm: this.searchKeyword
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list || [];
            this.totalPage = data.data.totalCount || 0
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },

      onSelectFilters (values) {
        this.selectFilters = values
      },
      rmFilters () {
        if (this.selectFilters.length < 1) {
          return this.$alert('请选择至少选择一个筛选项进行删除', '', {
            confirmButtonText: '确定'
          })
        }
        this.$confirm('是否删除选中的筛选项？', '', {
          confirmButtonText: '确认',
          cancelButtonText: '取消'
        }).then(() => {
          const ids = this.selectFilters.map(item => item.id)
          const params = {
            pIdLIist: ids
          }
          this.$http({
            url: this.$http.adornUrl('/prm-os-srv-prod/product/programDir/deleteAllProductProgramC'),
            method: 'post',
            data: this.$http.adornData(params)
          }).then(data => {
            if (data && data.code === 0) {
              this.getDataList();
            }
          })
        })
      },
      // 回车搜索
      async searchFilters () {
        if (!this.searchKeyword.trim()) {
          return this.$alert('请输入关键字进行搜索', '搜索方案', {
            confirmButtonText: '确定',
          })
        }
      },
      onCurrentChange (page) {
        this.currentPage = page
        this.getDataList()
      },
      // 显示添加的弹窗
      showAdd () {
        this.addDialog = true
      }
    }
  }
</script>

<style scoped>
  .filter-params{
    border: 1px solid #d5d5d5;
    margin-bottom: 8px;
  }
  .filter-params .el-icon-delete{
    color: #d2493f;
    cursor: pointer;
    font-size: 20px;
  }
  .filter-params >>> .el-row{
    padding: 8px 0;
    background-color: #eee;
  }
  .filter-params .filter-values{
    border-top: 1px solid #d5d5d5;
    background-color: #f5f5f5;
  }
  .filter-params .filter-values >>> .el-input-group__append{
    padding: 0 10px;
  }


  .filter-params >>> .el-form-item{
    padding-bottom: 12px;
    margin-bottom: 0;
  }

  .filter-values .value{
    display: inline-block;
    width: 110px;
    margin-right: 8px;
  }

  .mt20 {
    margin-top: 20px;
  }
</style>
